package algorithm.union;
/**
 * @author cyt
 * @create 2020-09-05 15:58
 */
public abstract class UnionFind {
    protected int[] parents;

    protected void rangeCheck(int index) {
        if (index < 0 || index > parents.length) {
            throw new IllegalArgumentException("数组越界");
        }
    }

    public UnionFind(int cap) {
        init(cap);
    }

    public boolean isSame(int v1, int v2) {
        int a = find(v1);
        int b = find(v2);
        return a == b;
    }

    /**
     * 合并
     *
     * @param a
     * @param b
     */
    public abstract void union(int a, int b);

    /**
     * 查找
     *
     * @param a
     * @return
     */
    public abstract int find(int a);

    /**
     * 初始化 集合
     *
     * @param cap
     */
    public void init(int cap) {
        parents = new int[cap];
        for (int i = 0; i < cap; i++) {
            parents[i] = i;
        }
    }

}
